<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Col,
  Descriptions,
  DescriptionsItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

import { getCapabilityInstances } from '#/api/resource-center';

import CapabilityInstanceEditor from './CapabilityInstanceEditor.vue';

// 响应式数据
const loading = ref(false);
const instanceList = ref([]);
const currentInstance = ref(null);
const detailModalVisible = ref(false);
const editorModalVisible = ref(false);

// 搜索表单
const searchForm = reactive({
  resourceId: '',
  capabilityId: '',
  status: '',
});

// 表格列定义
const columns = [
  {
    title: '实例名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '资源ID',
    dataIndex: 'resourceId',
    key: 'resourceId',
    width: 100,
  },
  {
    title: '能力类型',
    dataIndex: 'capabilityId',
    key: 'capabilityId',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '性能指标',
    key: 'performance',
    width: 150,
  },
  {
    title: '调用统计',
    key: 'metrics',
    width: 150,
  },
  {
    title: '操作',
    key: 'actions',
    width: 250,
    fixed: 'right',
  },
];

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    enabled: 'green',
    disabled: 'orange',
    error: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    enabled: '启用',
    disabled: '禁用',
    error: '错误',
  };
  return textMap[status] || status;
};

// 获取能力名称
const getCapabilityName = (capabilityId: string) => {
  const nameMap = {
    booking_capability: '预订能力',
    payment_capability: '支付能力',
    notification_capability: '通知能力',
    report_capability: '报表能力',
  };
  return nameMap[capabilityId] || capabilityId;
};

// 获取日志级别颜色
const getLogLevelColor = (level: string) => {
  const colorMap = {
    info: 'blue',
    warn: 'orange',
    error: 'red',
    debug: 'gray',
  };
  return colorMap[level] || 'default';
};

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString();
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const result = await getCapabilityInstances(searchForm);
    if (result.code === 200) {
      instanceList.value = result.data;
    }
  } catch (error) {
    console.error('加载能力实例失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  loadData();
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 查看详情
const viewDetail = (record: any) => {
  currentInstance.value = record;
  detailModalVisible.value = true;
};

// 编辑实例
const editInstance = (record: any) => {
  currentInstance.value = record;
  editorModalVisible.value = true;
};

// 测试实例
const testInstance = (record: any) => {
  message.info(`测试能力实例: ${record.name}`);
  // TODO: 实现能力实例测试功能TODOTODO
};

// 切换状态
const toggleStatus = (record: any) => {
  const newStatus = record.status === 'enabled' ? 'disabled' : 'enabled';
  newStatusrecord.statusnewStatusrecord.status;
  const action = newStatus === 'enabled' ? '启用' : '禁用';
  constactionnewStatusactionnewStatus;

  Modal.confirm({
    title: '确认操作',
    content: `确定要${action}能力实例 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        // TODO: 实现状态切换API调用
        record.status = newStatus;
        message.success(`${action}成功`);
      } catch {
        message.error(`${action}失败`);
      }
    },
  });
};

// 删除实例
const deleteInstance = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除能力实例 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        // TODO: 实现删除API调用
        message.success('删除成功');
        loadData();
      } catch {
        message.error('删除失败');
      }
    },
  });
};

// 新建能力实例
const openCreateModal = () => {
  currentInstance.value = null;
  editorModalVisible.value = true;
};

// 编辑器成功回调
const onEditorSuccess = () => {
  editorModalVisible.value = false;
  loadData();
  message.success('操作成功');
};

// 初始化
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="capability-instance-manager">
    <div class="manager-header">
      <h2>能力实例管理</h2>
      <div class="header-actions">
        <Button type="primary" @click="openCreateModal">
          <IconifyIcon icon="ant-design:plus-outlined" />
          新建能力实例
        </Button>
        <Button @click="refreshData">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新
        </Button>
      </div>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-section">
      <Row :gutter="16">
        <Col :span="6">
          <Input
            v-model:value="searchForm.resourceId"
            placeholder="搜索资源ID"
            allow-clear
            @change="handleSearch"
          />
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.capabilityId"
            placeholder="选择能力类型"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="booking_capability">预订能力</SelectOption>
            <SelectOption value="payment_capability">支付能力</SelectOption>
            <SelectOption value="notification_capability">
              通知能力
            </SelectOption>
            <SelectOption value="report_capability">报表能力</SelectOption>
          </Select>
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.status"
            placeholder="选择状态"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="enabled">启用</SelectOption>
            <SelectOption value="disabled">禁用</SelectOption>
            <SelectOption value="error">错误</SelectOption>
          </Select>
        </Col>
        <Col :span="4">
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
        </Col>
      </Row>
    </div>

    <!-- 能力实例列表 -->
    <div class="capability-instance-list">
      <Table
        :columns="columns"
        :data-source="instanceList"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>

          <template v-else-if="column.key === 'capabilityId'">
            <Tag color="blue">{{ getCapabilityName(record.capabilityId) }}</Tag>
          </template>

          <template v-else-if="column.key === 'performance'">
            <div class="performance-info">
              <div>响应时间: {{ record.state.performance.responseTime }}ms</div>
              <div>成功率: {{ record.state.performance.successRate }}%</div>
            </div>
          </template>

          <template v-else-if="column.key === 'metrics'">
            <div class="metrics-info">
              <div>总调用: {{ record.metrics.totalCalls }}</div>
              <div>成功: {{ record.metrics.successCalls }}</div>
              <div>失败: {{ record.metrics.failedCalls }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                <IconifyIcon icon="ant-design:eye-outlined" />
                查看
              </Button>
              <Button type="link" size="small" @click="editInstance(record)">
                <IconifyIcon icon="ant-design:edit-outlined" />
                编辑
              </Button>
              <Button type="link" size="small" @click="testInstance(record)">
                <IconifyIcon icon="ant-design:experiment-outlined" />
                测试
              </Button>
              <Button
                type="link"
                size="small"
                :danger="record.status === 'enabled'"
                @click="toggleStatus(record)"
              >
                <Icon
                  :icon="
                    record.status === 'enabled'
                      ? 'ant-design:pause-outlined'
                      : 'ant-design:play-outlined'
                  "
                />
                {{ record.status === 'enabled' ? '禁用' : '启用' }}
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="deleteInstance(record)"
              >
                <IconifyIcon icon="ant-design:delete-outlined" />
                删除
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </div>

    <!-- 能力实例详情模态框 -->
    <Modal
      v-model:visible="detailModalVisible"
      title="能力实例详情"
      width="800px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div v-if="currentInstance" class="instance-detail">
        <Descriptions :column="2" bordered>
          <DescriptionsItem label="实例名称">
            {{ currentInstance.name }}
          </DescriptionsItem>
          <DescriptionsItem label="资源ID">
            {{ currentInstance.resourceId }}
          </DescriptionsItem>
          <DescriptionsItem label="能力类型">
            <Tag color="blue">
              {{ getCapabilityName(currentInstance.capabilityId) }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="状态">
            <Tag :color="getStatusColor(currentInstance.status)">
              {{ getStatusText(currentInstance.status) }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="创建时间">
            {{ formatTime(currentInstance.createTime) }}
          </DescriptionsItem>
          <DescriptionsItem label="更新时间">
            {{ formatTime(currentInstance.updateTime) }}
          </DescriptionsItem>
        </Descriptions>

        <!-- 配置信息 -->
        <div class="section">
          <h3>配置信息</h3>
          <pre>{{
            JSON.stringify(currentInstance.configuration, null, 2)
          }}</pre>
        </div>

        <!-- 状态信息 -->
        <div class="section">
          <h3>状态信息</h3>
          <Descriptions :column="2" bordered>
            <DescriptionsItem label="可用性">
              <Tag :color="currentInstance.state.isAvailable ? 'green' : 'red'">
                {{ currentInstance.state.isAvailable ? '可用' : '不可用' }}
              </Tag>
            </DescriptionsItem>
            <DescriptionsItem label="最后检查时间">
              {{ formatTime(currentInstance.state.lastCheckTime) }}
            </DescriptionsItem>
            <DescriptionsItem label="响应时间">
              {{ currentInstance.state.performance.responseTime }}ms
            </DescriptionsItem>
            <DescriptionsItem label="吞吐量">
              {{ currentInstance.state.performance.throughput }}/s
            </DescriptionsItem>
            <DescriptionsItem label="成功率">
              {{ currentInstance.state.performance.successRate }}%
            </DescriptionsItem>
          </Descriptions>
        </div>

        <!-- 指标信息 -->
        <div class="section">
          <h3>指标信息</h3>
          <Descriptions :column="2" bordered>
            <DescriptionsItem label="总调用次数">
              {{ currentInstance.metrics.totalCalls }}
            </DescriptionsItem>
            <DescriptionsItem label="成功调用次数">
              {{ currentInstance.metrics.successCalls }}
            </DescriptionsItem>
            <DescriptionsItem label="失败调用次数">
              {{ currentInstance.metrics.failedCalls }}
            </DescriptionsItem>
            <DescriptionsItem label="平均响应时间">
              {{ currentInstance.metrics.averageResponseTime }}ms
            </DescriptionsItem>
            <DescriptionsItem label="最后调用时间">
              {{
                currentInstance.metrics.lastCallTime
                  ? formatTime(currentInstance.metrics.lastCallTime)
                  : '无'
              }}
            </DescriptionsItem>
          </Descriptions>
        </div>

        <!-- 日志信息 -->
        <div class="section">
          <h3>日志信息</h3>
          <div v-if="currentInstance.logs.length > 0">
            <div
              v-for="log in currentInstance.logs"
              :key="log.id"
              class="log-item"
            >
              <Tag :color="getLogLevelColor(log.level)" size="small">
                {{ log.level.toUpperCase() }}
              </Tag>
              <span class="log-time">{{ formatTime(log.timestamp) }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
          <div v-else class="empty-text">暂无日志</div>
        </div>
      </div>
    </Modal>

    <!-- 能力实例编辑模态框 -->
    <CapabilityInstanceEditor
      v-model:visible="editorModalVisible"
      :instance="currentInstance"
      @success="onEditorSuccess"
    />
  </div>
</template>

<style lang="less" scoped>
.capability-instance-manager {
  .manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 6px;
  }

  .capability-instance-list {
    .performance-info,
    .metrics-info {
      font-size: 12px;
      line-height: 1.4;
    }
  }

  .instance-detail {
    .section {
      margin-top: 24px;

      h3 {
        margin-bottom: 12px;
        color: #262626;
        font-size: 16px;
        font-weight: 500;
      }

      pre {
        background-color: #f5f5f5;
        padding: 12px;
        border-radius: 4px;
        font-size: 12px;
        color: #595959;
        overflow-x: auto;
      }

      .log-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
        padding: 8px;
        background-color: #f9f9f9;
        border-radius: 4px;

        .log-time {
          color: #8c8c8c;
          font-size: 12px;
        }

        .log-message {
          color: #262626;
          flex: 1;
        }
      }

      .empty-text {
        color: #8c8c8c;
        text-align: center;
        padding: 20px;
      }
    }
  }
}
</style>
